import { getInfo as baseGetInfo } from "@/api/login";
import store from "@/store";
import { getToken, isPlainObject } from "@/utils/common";
import requestApi from "@/utils/request";
import requestForCBApi from "@/utils/requestForCB";
import postMsgUtil from "./PostMsgUtil";

/**
 * 上传进度处理函数
 *
 * @param _onUploadProgress 上传进度回调函数
 * @param otherParams 其他参数
 * @param _params 参数对象
 * @param iframe iframe元素
 * @returns 返回处理结果对象，包含otherParamsTmp和_params两个属性
 */
function uploadProgress(_onUploadProgress, otherParams, params, iframe) {
  let otherParamsTmp = otherParams;
  if (_onUploadProgress) {
    // 转成formData
    let formData = new FormData();

    for (let _key in otherParams) {
      formData.append(_key, otherParams[_key]);
    }
    otherParamsTmp = formData;

    Object.assign(params, {
      onUploadProgress: (progressEvent) => {
        const { loaded, total } = progressEvent;

        // iframe 拼接方式 iframeId&&自定义的其他值
        iframe = document.getElementById(_onUploadProgress.split("&&")[0]);
        iframe
          ? postMsgUtil.trigger(iframe, _onUploadProgress, {
              data: { loaded, total },
            })
          : "";
      },
    });
  }

  return {
    otherParamsTmp,
    params,
  };
}

/**
 * 下载进度
 *
 * @param _onDownloadProgress 下载进度回调函数
 * @param params 参数对象
 * @param iframe iframe元素
 * @returns 返回修改后的参数对象
 */
function downloadProgress(_onDownloadProgress, params, iframe) {
  if (_onDownloadProgress) {
    Object.assign(params, {
      onDownloadProgress: (progressEvent) => {
        const { loaded, total } = progressEvent;

        // iframe 拼接方式 iframeId&&自定义的其他值
        iframe = document.getElementById(_onDownloadProgress.split("&&")[0]);
        iframe
          ? postMsgUtil.trigger(iframe, _onDownloadProgress, {
              data: { loaded, total },
            })
          : "";
      },
    });
  }

  return {
    params,
  };
}

/**
 * 通用请求父框架的request
 * @param {String} url 请求地址
 * @param {Object} params 请求参数
 * @param {Object} headers Headers
 * @param {String} method 请求方式
 * @returns
 */
function request(
  url,
  params = {},
  headers = {},
  method = "get",
  responseType = "json"
) {
  const methodsMap = {
    getInfo: () => {
      return getInfo();
    },
    getPermissionsByTarget: () => {
      return getPermissionsByTarget();
    },
  };
  if (["getInfo", "getPermissionsByTarget"].includes(url)) {
    return methodsMap[url]();
  } else {
    let _params = {
      url,
      method,
      headers,
      responseType,
    };
    let otherParamsTmp = params;
    if (isPlainObject(params)) {
      // 增加上传/下载监听 2023.11.01
      let { _onUploadProgress, _onDownloadProgress, ...otherParams } = params;
      otherParamsTmp = otherParams;
      let iframe = null;
      // 上传
      const uploadResult = uploadProgress(
        _onUploadProgress,
        otherParams,
        _params,
        iframe
      );
      Object.assign(_params, uploadResult.params);
      otherParamsTmp = uploadResult.otherParamsTmp;

      // 下载
      const downloadResult = downloadProgress(
        _onDownloadProgress,
        _params,
        iframe
      );
      Object.assign(_params, downloadResult.params);
    }

    _params =
      method === "get"
        ? Object.assign({}, _params, { params: otherParamsTmp })
        : Object.assign({}, _params, { data: otherParamsTmp });
    if (!params?.__ctCbAllCode) {
      return requestApi(_params);
    } else {
      return requestForCBApi(_params);
    }
  }
}

/**
 * 获取用户信息
 * @returns
 */
async function getInfo() {
  if (store.state?.user?.userInfo) {
    return new Promise((resolve) => {
      resolve({
        code: 200,
        msg: "操作成功",
        user: { ...store.state.user.userInfo, token: getToken() },
        deptInfo: store.state.user.deptInfo,
      });
    });
  } else {
    const { user = {}, ...other } = await baseGetInfo();
    user.token = getToken();
    return {
      ...other,
      user,
    };
  }
}

/**
 * 根据标识查下出权限节点
 */
function getPermissionsByTarget() {
  if (store.state?.user?.permissions) {
    return new Promise((resolve) => {
      resolve({
        code: 200,
        msg: "操作成功",
        permissions: store.state.user.permissions,
      });
    });
  } else {
    return new Promise((resolve) => {
      resolve({
        code: 200,
        msg: "操作成功",
        permissions: {},
      });
    });
  }
}

/**
 * 判断是否是同域，是/否都通过postMessage优先发送一条通讯信息
 * @param {*} url
 * @param {*} iframeId
 * @param {*} fn
 */
function checkCross(url, iframeId) {
  // 获取当前的URL地址
  const parentUrl = `${window.location.protocol}//${window.location.host}`;

  postMsgUtil.trigger(
    iframeId,
    "checkCross",
    { data: parentUrl === url ? 200 : 201, type: "S-IFRAME" },
    (data) => {
      console.log(
        `[${iframeId}] parent postmessage trigger checkCross callback`,
        data
      );
    }
  );
}

export default {
  request,
  checkCross,
};
